# Load packages
  library(tidyverse)
  library(haven)
  library(car)
  library(broom)
  library(lmtest)
  library(sandwich)
  library(stargazer)
  
# Calculate robust confidence intervals
  se_robust <- function(x)
    coeftest(x, vcov = vcovHC(x, type = "HC0"))[, "Std. Error"]
  p_robust <- function(x)
    coeftest(x, vcov = vcovHC(x, type = "HC0"))[, "Pr(>|t|)"]

  #### AUTNES Multi-Mode Panel Study 2017
  
  # Load data
  dt <- read_dta("ObsStudy_00_data_Austria_AUTNES_Multi_Mode_Panel_2017.dta")
  
  # Wave 1
  # Party rating: Generate party rating as distance measure retrieved from left-right party placement and self-placement 
  dt[, 82:87][dt[, 82:87] >= 77] <- NA
  dt[, 88][dt[, 88] >= 77] <- NA
  
  # Party rating SPO
  dt$rat_SPO <- abs(dt$w1_q12 - dt$w1_q11x1)^2
  # Recode, so large distance value is a low value on party rating variable
  dt$rat_SPO = recode(dt$rat_SPO, "0=10; 1=9; 2=8; 3=7; 4=6; 5=5; 6=4; 7=3; 8=2; 9=1; 10=0")

  # Party rating OVP
  dt$rat_OVP <- abs(dt$w1_q12 - dt$w1_q11x2)^2
  # Recode, so large distance value is a low value on party rating variable
  dt$rat_OVP = recode(dt$rat_OVP, "0=10; 1=9; 2=8; 3=7; 4=6; 5=5; 6=4; 7=3; 8=2; 9=1; 10=0")

  # Party rating FPO
  dt$rat_FPO <- abs(dt$w1_q12 - dt$w1_q11x3)^2
  # Recode, so large distance value is a low value on party rating variable
  dt$rat_FPO = recode(dt$rat_FPO, "0=10; 1=9; 2=8; 3=7; 4=6; 5=5; 6=4; 7=3; 8=2; 9=1; 10=0")

  # Party rating GRUENE
  dt$rat_GRUENE <- abs(dt$w1_q12 - dt$w1_q11x4)^2
  # Recode, so large distance value is a low value on party rating variable
  dt$rat_GRUENE = recode(dt$rat_GRUENE, "0=10; 1=9; 2=8; 3=7; 4=6; 5=5; 6=4; 7=3; 8=2; 9=1; 10=0")

  # Party rating NEOS
  dt$rat_NEOS <- abs(dt$w1_q12 - dt$w1_q11x5)^2
  # Recode, so large distance value is a low value on party rating variable
  dt$rat_NEOS = recode(dt$rat_NEOS, "0=10; 1=9; 2=8; 3=7; 4=6; 5=5; 6=4; 7=3; 8=2; 9=1; 10=0")
  
  # Coalition evaluations/preferred coalition
  # SPOE-OEVP,  w2_q20x1 / OEVP-FPOE, w2_q20x2 / SPOE-FPOE, w2_q20x3 
  
  colnames(dt)[seq(284, 286, 1)] <- c("rat_coal_SPO_OVP", "rat_coal_OVP_FPO", "rat_coal_SPO_FPO")
  dt[, 284:286][dt[, 284:286] >= 77] <- NA
  
  # Coalition likelihood
  # SPOE-OEVP, w2_q19x1 / OEVP-FPOE, w2_q19x2 / SPOE-FPOE, w2_q19x3 
  colnames(dt)[seq(281, 283, 1)] <- c("coallik_SPO_OVP", "coallik_OVP_FPO", "coallik_SPO_FPO")
  dt[, 281:283][dt[, 281:283] >= 77] <- NA
  
  # Dependent Variable: binary vote choice
  # Q16. [WENN Q15 = 4, 5, 6, 7, 8, 9, 10]: Und welcher Partei werden Sie bei der Nationalratswahl voraussichtlich Ihre Stimme geben?
  # Q17. [WENN Q15 < 4 oder 88]: Angenommen Sie w?rden an der Nationalratswahl teilnehmen, f?r welche Partei w?rden Sie sich am ehesten entscheiden?
  dt$w2_q16[dt$w2_q16 >= 77] <- NA
  dt$w2_q17[dt$w2_q17 >= 77] <- NA
  
  # Generate party choice variable
  dt$vote <- dt$w2_q16
  dt$vote <- ifelse(is.na(dt$vote), dt$w2_q17, dt$vote)
  
  # Generate ptv columns based on vote variable
  dt$vc_SPO <- ifelse(dt$vote == 1, 1, 0)
  dt$vc_OVP <- ifelse(dt$vote == 2, 1, 0)
  dt$vc_FPO <- ifelse(dt$vote == 3, 1, 0)
  
  
  # Coalition evaluation, note that coalition likelihoods only for three coalition options available
  Z <- dt %>% select(contains("rat_coal")) %>%
    mutate_all(as.numeric) %>%
    mutate_all(funs(scales::rescale(.,to = c(0, 1))))
  
  rat_coal_SPO <- Z %>% select(rat_coal_SPO_OVP, rat_coal_SPO_FPO) %>% as.matrix()
  rat_coal_OVP <- Z %>% select(rat_coal_SPO_OVP, rat_coal_OVP_FPO) %>% as.matrix()
  rat_coal_FPO <- Z %>% select(rat_coal_OVP_FPO, rat_coal_SPO_FPO) %>% as.matrix()
  
  
  # Coalition likelihood
  gamma <- dt %>% select(contains("coallik_")) 
  
  coal_lik_SPO <- gamma %>% select(coallik_SPO_OVP, coallik_SPO_FPO) %>%
    mutate(sum_exp = exp(coallik_SPO_OVP) + exp(coallik_SPO_FPO),
           coallik_SPO_OVP = exp(coallik_SPO_OVP)/sum_exp,
           coallik_SPO_FPO = exp(coallik_SPO_FPO)/sum_exp) %>%
    select(-sum_exp) %>%
    as.matrix()
  
  
  coal_lik_OVP <- gamma %>% select(coallik_SPO_OVP, coallik_OVP_FPO) %>%
    mutate(sum_exp = exp(coallik_SPO_OVP) + exp(coallik_OVP_FPO),
           coallik_SPO_OVP = exp(coallik_SPO_OVP) / sum_exp,
           coallik_OVP_FPO = exp(coallik_OVP_FPO) / sum_exp) %>%
    select(-sum_exp)  %>%
    as.matrix()
  
  
  coal_lik_FPO <- gamma %>% select(coallik_OVP_FPO, coallik_SPO_FPO) %>%
    mutate(sum_exp = exp(coallik_OVP_FPO) + exp(coallik_SPO_FPO),
           coallik_OVP_FPO = exp(coallik_OVP_FPO) / sum_exp,
           coallik_SPO_FPO = exp(coallik_SPO_FPO) / sum_exp) %>%
    select(-sum_exp) %>%
    as.matrix()
  
  
  # Mean-variance model
  EV <- function(gamma,Z){
    gamma %*% Z
  }
  
  Vari <- function(gamma,Z){
    gamma %*% ((Z - as.numeric(EV(gamma,Z)))^2)
  }
  
  N <- nrow(dt)
  
  M_SPO <- sapply(1:N, function(i) EV(coal_lik_SPO[i,], rat_coal_SPO[i,]))
  V_SPO <- sapply(1:N, function(i) Vari(coal_lik_SPO[i,], rat_coal_SPO[i,]))
  
  M_OVP <- sapply(1:N, function(i) EV(coal_lik_OVP[i,], rat_coal_OVP[i,]))
  V_OVP <- sapply(1:N, function(i) Vari(coal_lik_OVP[i,], rat_coal_OVP[i,]))
  
  M_FPO <- sapply(1:N, function(i) EV(coal_lik_FPO[i,], rat_coal_FPO[i,]))
  V_FPO <- sapply(1:N, function(i) Vari(coal_lik_FPO[i,], rat_coal_FPO[i,]))
  
  
  # Gender variable, 1 = male, 2 = female
  dt$male <- ifelse(dt$gender == 2, 0, dt$gender)
  dt$male <- ifelse(dt$male==99, NA, dt$male)

  # Education
  # Set missings or observations that do not fit the scheme to NA
  dt$w1_sd6 <- ifelse(dt$w1_sd6 > 15, NA, dt$w1_sd6)
  
  # PID
  if (!exists("robustnesscheck_pid")) {
    robustnesscheck_pid <- FALSE # PID as robustness?
  }
  dt$w1_q15[dt$w1_q14==2] <- 0
  dt$pid_SPO <- ifelse(dt$w1_q15==1, 1, 0)
  dt$pid_OVP <- ifelse(dt$w1_q15==2, 1, 0)
  dt$pid_FPO <- ifelse(dt$w1_q15==3, 1, 0)
  
  d <- data.frame(
    "vc_SPO" = dt$vc_SPO,
    "vc_OVP" = dt$vc_OVP,
    "vc_FPO" = dt$vc_FPO,
    "rat.SPO" = dt$rat_SPO,
    "rat.OVP" = dt$rat_OVP,
    "rat.FPO" = dt$rat_FPO,
    "rat.GRUENE" = dt$rat_GRUENE,
    "pid_SPO" = dt$pid_SPO,
    "pid_OVP" = dt$pid_OVP,
    "pid_FPO" = dt$pid_FPO,
    "lotterymean.SPO" = M_SPO,
    "lotteryvariance.SPO" = V_SPO,
    "lotterymean.OVP" = M_OVP,
    "lotteryvariance.OVP" = V_OVP,
    "lotterymean.FPO" = M_FPO,
    "lotteryvariance.FPO" = V_FPO,
    "sex" = dt$male,
    "age" = dt$age,
    "edu" = dt$w1_sd6,
    "rat_leader_SPO" = ifelse(dt$w2_q12x1<11, dt$w2_q12x1, NA),
    "rat_leader_OVP" = ifelse(dt$w2_q12x2<11, dt$w2_q12x2, NA),
    "rat_leader_FPO" = ifelse(dt$w2_q12x3<11, dt$w2_q12x3, NA)
  )  
  
  d$lotteryvariance.SPO <- scales::rescale(d$lotteryvariance.SPO, to = c(0, 1), from = c(0,0.25))
  d$lotteryvariance.OVP <- scales::rescale(d$lotteryvariance.OVP, to = c(0, 1), from = c(0,0.25))
  d$lotteryvariance.FPO <- scales::rescale(d$lotteryvariance.FPO, to = c(0, 1), from = c(0,0.25))
  
# Save model results
  summary(m1 <- lm(as.formula(paste("vc_SPO ~ lotteryvariance.SPO + lotterymean.SPO + rat.SPO + rat_leader_SPO + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_SPO" else "")), d))
  summary(m2 <- lm(as.formula(paste("vc_OVP ~ lotteryvariance.OVP + lotterymean.OVP + rat.OVP + rat_leader_OVP + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_OVP" else "")), d))
  summary(m3 <- lm(as.formula(paste("vc_FPO ~ lotteryvariance.FPO + lotterymean.FPO + rat.FPO + rat_leader_FPO + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_FPO" else "")), d))
  
  AUT_2017_AUTNES_MMP_SPO_Variance_Estimate <- tidy(m1) %>% filter(term=="lotteryvariance.SPO") %>% select("estimate")
  AUT_2017_AUTNES_MMP_SPO_Variance_SE <- se_robust(m1)["lotteryvariance.SPO"]
  AUT_2017_AUTNES_MMP_SPO_Mean_Estimate <- tidy(m1) %>% filter(term=="lotterymean.SPO") %>% select("estimate")
  AUT_2017_AUTNES_MMP_SPO_Mean_SE <- se_robust(m1)["lotterymean.SPO"]
  
  AUT_2017_AUTNES_MMP_OVP_Variance_Estimate <- tidy(m2) %>% filter(term=="lotteryvariance.OVP") %>% select("estimate")
  AUT_2017_AUTNES_MMP_OVP_Variance_SE <- se_robust(m2)["lotteryvariance.OVP"]
  AUT_2017_AUTNES_MMP_OVP_Mean_Estimate <- tidy(m2) %>% filter(term=="lotterymean.OVP") %>% select("estimate")
  AUT_2017_AUTNES_MMP_OVP_Mean_SE <- se_robust(m2)["lotterymean.OVP"]
  
  AUT_2017_AUTNES_MMP_FPO_Variance_Estimate <- tidy(m3) %>% filter(term=="lotteryvariance.FPO") %>% select("estimate")
  AUT_2017_AUTNES_MMP_FPO_Variance_SE <- se_robust(m3)["lotteryvariance.FPO"]
  AUT_2017_AUTNES_MMP_FPO_Mean_Estimate <- tidy(m3) %>% filter(term=="lotterymean.FPO") %>% select("estimate")
  AUT_2017_AUTNES_MMP_FPO_Mean_SE <- se_robust(m3)["lotterymean.FPO"]
  
  # Harmonize names of the IVs of interest in the models
  names(m1$coefficients)[names(m1$coefficients) == "lotteryvariance.SPO"] <- "Government Lottery Variance"
  names(m1$coefficients)[names(m1$coefficients) == "lotterymean.SPO"] <- "Government Lottery Mean"
  names(m2$coefficients)[names(m2$coefficients) == "lotteryvariance.OVP"] <- "Government Lottery Variance"
  names(m2$coefficients)[names(m2$coefficients) == "lotterymean.OVP"] <- "Government Lottery Mean"
  names(m3$coefficients)[names(m3$coefficients) == "lotteryvariance.FPO"] <- "Government Lottery Variance"
  names(m3$coefficients)[names(m3$coefficients) == "lotterymean.FPO"] <- "Government Lottery Mean"

  
  if(!robustnesscheck_pid){
    stargazer(m1, m2, m3, title="Linear regressions of vote choice on perceived government lottery variance and mean (AUTNES Multi-Mode Panel Study 2017, Wave 2)", 
              align=TRUE, 
              dep.var.labels=c("SPO", "OVP", "FPO"),
              omit.stat=c("LL","ser","f"),
              se = lapply(list(m1, m2, m3), se_robust),
              p = lapply(list(m1, m2, m3), p_robust),
              out = "TableSM3.tex")
  }
 
